import {
  View,
  Text,
  ImageBackground,
  StyleSheet,
  Platform,
  ScrollView,
  TextInput,
  Dimensions,
  TouchableOpacity,
  Alert,
} from 'react-native';
import React, {useState} from 'react';
import * as Animatable from 'react-native-animatable';
import Ionicons from 'react-native-vector-icons/Ionicons';
import LinearGradient from 'react-native-linear-gradient';

import {connect} from 'react-redux';
import {userLogin} from '../../store/action/user';

const mapStateToProps = state => {
  return {
    user: state.userOp.userInfo,
  };
};
export default connect(mapStateToProps, {userLogin})(Login);
function Login({navigation, userInfo, userLogin}) {
  const [userName, setUserName] = useState({
    name: '',
    validateName: false,
    isValidate: true,
  });
  const [password, setPassword] = useState({
    passwordVal: '',
    validatePassword: false,
    isValidate: true,
  });
  const [secureTextEntry, setSecureTextEntry] = useState(true);
  return (
    <View style={[styles.container]}>
      <ImageBackground
        source={require('../../images/bg2.jpg')}
        style={[styles.bgImage]}>
        <View style={[styles.header]}>
          <Text style={[styles.headerText]}>WelCome!</Text>
        </View>
        <Animatable.View animation="fadeInUpBig" style={[styles.footer]}>
          <ScrollView>
            <View style={[styles.action]}>
              <Ionicons name={'person-outline'} size={20} />
              <TextInput
                style={[styles.input]}
                placeholder="请输入用户名"
                value={userName.name}
                onChangeText={text => validateName(text)}
                underlineColorAndroid={
                  userName.isValidate ? 'transparent' : 'red'
                }
                onEndEditing={e => handleValidateUser(e.nativeEvent.text)}
              />
              {userName.validateName ? (
                <Animatable.View animation={'bounceIn'}>
                  <Ionicons name="checkmark-circle-outline" size={20} />
                </Animatable.View>
              ) : null}
            </View>
            {userName.isValidate ? null : (
              <Animatable.View animation={'fadeInLeft'} duration={500}>
                <Text style={[styles.errorMsg]}>用户名最短是2位</Text>
              </Animatable.View>
            )}
            <View style={[styles.action]}>
              <Ionicons name={'lock-closed-outline'} size={20} />
              <TextInput
                style={[styles.input]}
                placeholder="请输入密码"
                value={password.passwordVal}
                secureTextEntry={secureTextEntry ? true : false}
                onChangeText={text => validatePassword(text)}
                underlineColorAndroid={
                  password.isValidate ? 'transparent' : 'red'
                }
              />
              <TouchableOpacity
                onPress={() => setSecureTextEntry(!secureTextEntry)}>
                {secureTextEntry ? (
                  <Ionicons name="eye-off-outline" size={20} />
                ) : (
                  <Ionicons name="eye-outline" size={20} />
                )}
              </TouchableOpacity>
            </View>
            {password.isValidate ? null : (
              <Animatable.View animation={'fadeInLeft'} duration={500}>
                <Text style={[styles.errorMsg]}>密码最短是8位</Text>
              </Animatable.View>
            )}
            <View style={[styles.button]}>
              <TouchableOpacity
                style={styles.signIn}
                onPress={() => this.handleLogin()}>
                <LinearGradient
                  colors={['#08d4c4', '#01ab9d']}
                  style={[styles.signIn]}>
                  <Text style={[styles.textSign, {color: '#fff'}]}>登录</Text>
                </LinearGradient>
              </TouchableOpacity>
              <TouchableOpacity
                onPress={() => navigation.navigate('Register')}
                style={[
                  styles.signIn,
                  {borderColor: '#009387', borderWidth: 1, marginTop: 15},
                ]}>
                <Text style={[styles.textSign, {color: '#009387'}]}>注册</Text>
              </TouchableOpacity>
            </View>
          </ScrollView>
        </Animatable.View>
      </ImageBackground>
    </View>
  );
  function validateName(val) {
    if (val.trim().length >= 2) {
      setUserName({
        ...userName,
        name: val,
        validateName: true,
        isValidate: true,
      });
    } else {
      setUserName({
        ...userName,
        name: val,
        validateName: false,
        isValidate: false,
      });
    }
  }

  function handleValidateUser(val) {
    if (val.trim().length >= 2) {
      setUserName({...userName, isValidate: true});
    } else {
      setUserName({...userName, isValidate: false});
    }
  }
  function validatePassword(val) {
    if (val.trim().length >= 8) {
      setPassword({
        passwordVal: val,
        validatePassword: true,
        isValidate: true,
      });
    } else {
      setPassword({
        passwordVal: val,
        validatePassword: false,
        isValidate: false,
      });
    }
  }

  function handleLogin() {
    if (userName.name.length == 0 || password.passwordVal.length == 0) {
      Alert.alert('输入错误', '用户和密码不能为空');
      return;
    }
    if (userName.name.length < 2) {
      Alert.alert('用户名太短', '用户名最短2位');
      return;
    }
    if (password.passwordVal.length < 8) {
      Alert.alert('密码太短', '密码最短8位');
      return;
    }
    let userInfo = {
      username: userName.name,
      password: password.passwordVal,
    };
    Login(userInfo);
    Alert.alert('登录成功');
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
  },
  bgImage: {
    flex: 1,
    resizeMode: 'cover',
    justifyContent: 'center',
  },
  header: {
    flex: 1,
    justifyContent: 'flex-end',
    paddingHorizontal: 20,
    paddingBottom: Platform.OS === 'ios' ? 150 : 100,
  },
  headerText: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 30,
    textAlign: 'center',
  },
  footer: {
    flex: 3,
    backgroundColor: '#fff',
    borderTopLeftRadius: 40,
    borderTopRightRadius: 40,
    paddingHorizontal: 20,
    paddingVertical: 30,
  },
  input: {
    flex: 1,
    marginTop: Platform.OS === 'ios' ? 0 : -12,
    paddingLeft: 10,
    // color: '#055375a',
  },
  action: {
    flexDirection: 'row',
    marginTop: 5,
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    paddingBottom: 5,
  },
  errorMsg: {
    color: 'red',
    fontSize: 14,
  },
  button: {
    flexDirection: 'column',
    justifyContent: 'center',
  },
  signIn: {
    height: 45,
    width: Dimensions.get('window').width - 50,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
  },
  textSign: {
    fontSize: 23,
  },
  button: {
    flexDirection: 'column',
    justifyContent: 'center',
  },
  signIn: {
    height: 45,
    width: Dimensions.get('window').width - 50,
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10,
  },
  textSign: {
    fontSize: 23,
  },
});
